'use strict';

//龚hi 英语8级，不消说了嘛
// All this does is allow the message
// to be sent when you tap return
ionicTea.directive('input', function ($timeout) {
  return {
    restrict: 'E',
    scope: {
      'returnClose': '=',
      'onReturn': '&',
      'onFocus': '&',
      'onBlur': '&'
    },
    link: function link(scope, element, attr) {
      element.bind('focus', function (e) {
        if (scope.onFocus) {
          $timeout(function () {
            scope.onFocus();
          });
        }
      });
      element.bind('blur', function (e) {
        if (scope.onBlur) {
          $timeout(function () {
            scope.onBlur();
          });
        }
      });
      element.bind('keydown', function (e) {
        if (e.which == 13) {
          if (scope.returnClose) element[0].blur();
          if (scope.onReturn) {
            $timeout(function () {
              scope.onReturn();
            });
          }
        }
      });
    }
  };
});

ionicTea.controller('ChatCtrl', function ($scope, $rootScope, $state, $stateParams, $ionicHistory, $ionicScrollDelegate, $timeout, MsgService, UserService, ImageService) {

	$scope.goToUserDetailPage = function (id) {
			if(id)
			UserService.goToUserDetailPage(id);
	};

  $scope.back = function () {
    //为了下次进来是在 最新聊天处
    $ionicScrollDelegate.scrollBottom(true);
    $rootScope.back();
  };

  var targetId = $stateParams.id;
  var loginUser = UserService.getUserAcceptCache();

  //聊天内容
  $scope.chatMsg = [];
  //聊天内容
  $scope.msgData;

  var isIOS = ionic.Platform.isWebView() && ionic.Platform.isIOS();

  var msgCallback = {
    success: function success(msgs) {
      // add msgs
      $scope.$apply(function () {

        var length = msgs.length;
        console.log('msgs = ' + JSON.stringify(msgs));
        console.log('msgs.length = ' + msgs.length);
        var pos = 0;
        for (; pos < length; pos++) {

          var msgUser = JSON.parse(msgs[pos].content.extra);

          $scope.chatMsg.push({
            headImg: msgUser.avatar,
            dir: msgs[pos].messageDirection === 'RECEIVE',
            msgContent: msgs[pos].content == null ? '' : msgs[pos].content.text,
            isImage: msgs[pos].objectName == 'RC:ImgMsg',
            image: msgs[pos].objectName == 'RC:ImgMsg' ? msgs[pos].content.imageUrl: '',
          });

        }
      });
    },
    failed: function failed(err) {}
  };

  console.log('set onReceiveListener');
  // $scope.$on("$destroy", function() {
  //   console.log('$destroy');
  //   $rootScope.setListener();
  // });

  var receiverModel = {};
  receiverModel.name = 'chat';
  receiverModel.receiver = function(ret) {
    if ($state.is('chat')) {
      if (ret.result.message.targetId != targetId) return;

      var msgUser = JSON.parse(ret.result.message.content.extra);

      $scope.$apply(function () {
        $scope.chatMsg.push({
          headImg: msgUser.avatar,
          dir: true,
          msgContent: ret.result.message.content == null ? '' : ret.result.message.content.text,
          isImage: ret.result.message.objectName == 'RC:ImgMsg',
          image: ret.result.message.objectName == 'RC:ImgMsg' ? ret.result.message.content.imageUrl: '',
        });

        //滚动到最下方
        $ionicScrollDelegate.scrollBottom(true);
      });

    }
  }
  $rootScope.addReceiver(receiverModel);

  // RongCloudLibPlugin.setOnReceiveMessageListener(function (ret, err) {
  //   console.log('onReceiveListener chat');
  //   if (err) {
  //     console.log(JSON.stringify(err));
  //     return;
  //   }
  //
  //   if (ret.result.message.targetId != targetId) return;
  //
  //   var msgUser = JSON.parse(ret.result.message.content.extra);
  //
  //
  //
  //   $scope.$apply(function () {
  //     $scope.chatMsg.push({
  //       headImg: msgUser.avatar,
  //       dir: true,
  //       msgContent: ret.result.message.content.text
  //     });
  //
  //     //滚动到最下方
  //     $ionicScrollDelegate.scrollBottom(true);
  //   });
  //
  // });

  var loadHistoryMsg = function loadHistoryMsg(targetId, time) {
    MsgService.getHistoryMessage(targetId, time, msgCallback);
  };

  var loadLastestMsg = function loadLastestMsg(targetId) {
    MsgService.getLastestMessages(targetId, msgCallback);
  };

  //so 加载聊天记录吧
  $scope.loadChatMsg = function () {

    if ($scope.chatMsg.length == 0) {
      // loadHistoryMsg(targetId, 0);
      loadLastestMsg(targetId);
    } else {}

    //get信息    dir:true-收到的信息    dir:false-发出的信息
    // var msgData = [
    // 	{
    // 		headImg:'img/mike.png',
    // 		dir:true,
    // 		msgContent:'天气这么好，出来喝茶啊，昊雨'
    // 	},
    // 	{
    // 		headImg:'img/perry.png',
    // 		dir:false,
    // 		msgContent:'喝屁啊，下午要写作业'
    // 	},
    // 	{
    // 		headImg:'img/mike.png',
    // 		dir:true,
    // 		msgContent:'我下午没课，一起去上自习吧，顺便喝茶'
    // 	},
    // 	{
    // 		headImg:'img/perry.png',
    // 		dir:false,
    // 		msgContent:'一起自习还写得进屁的作业啊'
    // 	}
    // ];
    //
    // var msgLength = msgData.length;
    //
    // for(var i=0;i < msgLength;i++){
    //
    // 	$scope.chatMsg.push(msgData[i]);
    // }
  };

  // 单聊发送图片
  $scope.sendImage = function() {
    var callback = {
      success: function(imageURI) {

        var msg = {
          conversationType: 'PRIVATE',
          targetId: targetId,
          imagePath: imageURI,
          extra: ''
        };

        msg.extra = {};
        msg.extra = loginUser;

         $scope.chatMsg.push({
            headImg: loginUser.avatar,
            dir: false,
            isImage: true,
            image: imageURI,
          });

        RongCloudLibPlugin.sendImageMessage(msg, function (ret, err) {
            if (ret.status == 'prepare') {

            }
                // alert(JSON.stringify(ret.result.message) );
            else if (ret.status == 'progress') {

            }
                // alert(ret.result.progress );
            else if (ret.status == 'success')
                alert(ret.result.message.messageId );
            else if (ret.status == 'error')
                alert(err.code );
          }
        );
      },
    };

    ImageService.pickImage(callback);
   }

  //发送消息
  $scope.sendMessage = function () {

    if ($scope.msgData.message == null || $scope.msgData.message.length <= 0) {
      return;
    }
    console.log("发送：" + $scope.msgData.message);

    var tempUser = UserService.getUserAcceptCache();

    $scope.chatMsg.push({
      headImg: tempUser.avatar,
      dir: false,
      msgContent: $scope.msgData.message,
      isImage: false,
      image: '',
    });

    $scope.msgData.extra = loginUser;

    MsgService.sendMessage(targetId, $scope.msgData);

    delete $scope.msgData.message;
    //滚动到最下方
    $ionicScrollDelegate.scrollBottom(true);
  };

  $scope.inputUp = function () {
    if (isIOS) $scope.data.keyboardHeight = 216;
    $timeout(function () {
      $ionicScrollDelegate.scrollBottom(true);
    }, 300);
  };

  $scope.inputDown = function () {
    if (isIOS) $scope.data.keyboardHeight = 0;
    $ionicScrollDelegate.resize();
  };

  $scope.closeKeyboard = function () {

    //加不加吧  我也认不得
    // cordova.plugins.Keyboard.close();
  };

  //收到消息，天啦噜~
  $scope.receiveMessage = function () {

    //天啦噜，测试下接收

    $scope.chatMsg.push({
      headImg: 'img/mike.png',
      dir: true,
      msgContent: '你说锤子，我听不懂！'
    });
    //滚动到最下方
    $ionicScrollDelegate.scrollBottom(true);
  };
});

ionicTea.controller('GroupCtrl', function ($scope, $state, $stateParams,$rootScope, $ionicHistory, HttpUploadService, $ionicSlideBoxDelegate, UserService, HttpService, $cordovaCamera, $ionicActionSheet) {
  $scope.groupModel = {};

  $scope.goToCreateGroup = function () {
    $state.go('create_group');
  };

  $scope.goToChatGroup = function (id) {
    RongCloudLibPlugin.clearMessagesUnreadStatus({
        conversationType: 'GROUP',
        targetId: id,
      }, function (ret, err) {
          // alert(ret.status);
    });

    $state.go('chat_group', { id: id });
  };

  $scope.goToChatGroupDetail = function (id, isMember) {
    if (isMember) {
      $scope.goToChatGroup(id);
    } else {
      $state.go('chat-group-detail', { id: id });
    }

  };

  $scope.group_logo = 'img/friends/create_group.png';

    //选择相册或者拍照
    $scope.selectImgType = function () {

        // 显示操作表
        $ionicActionSheet.show({
            cssClass: "user-sheet",
            buttons: [{ text: '拍照' }, { text: '从相册选择' }],
            titleText: '选择图片',
            cancelText: '取消',
            buttonClicked: function buttonClicked(index) {
                if (index == 0) {
                    $scope.takePhoto();
                }
                if (index == 1) {
                    $scope.from_gallery();
                }
                return true;
            }
        });
    };

    //相册选择
    $scope.from_gallery = function () {

        // destinationType: Camera.DestinationType.FILE_URI,
        var options = {
              targetWidth: 200, //照片宽度
            targetHeight: 200, //照片高度
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
        };

        $cordovaCamera.getPicture(options).then(function (imageURI) {
            $scope.group_logo = imageURI;
        }, function (err) {
            // error
        });
    };

    //拍照
    $scope.takePhoto = function () {

        var options = {
            quality: 100, //相片质量0-100
            destinationType: Camera.DestinationType.FILE_URI, //返回类型：DATA_URL= 0，返回作为 base64 編碼字串。 FILE_URI=1，返回影像档的 URI。NATIVE_URI=2，返回图像本机URI (例如，資產庫)
            sourceType: Camera.PictureSourceType.CAMERA, //从哪里选择图片：PHOTOLIBRARY=0，相机拍照=1，SAVEDPHOTOALBUM=2。0和1其实都是本地图库
            allowEdit: false, //在选择之前允许修改截图
            encodingType: Camera.EncodingType.JPEG, //保存的图片格式： JPEG = 0, PNG = 1
            targetWidth: 200, //照片宽度
            targetHeight: 200, //照片高度
            mediaType: 0, //可选媒体类型：圖片=0，只允许选择图片將返回指定DestinationType的参数。 視頻格式=1，允许选择视频，最终返回 FILE_URI。ALLMEDIA= 2，允许所有媒体类型的选择。
            cameraDirection: 0, //枪后摄像头类型：Back= 0,Front-facing = 1
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        };

        $cordovaCamera.getPicture(options).then(function (imageURI) {
            $scope.group_logo = imageURI;
        }, function (err) {});
    };

  $scope.createGroup = function () {

    var user = UserService.getUserAcceptCache();

    var callback = {
      success: function success(data) {
        $state.go('group_list');

        // 添加到荣云服务器
        RongCloudLibPlugin.joinGroup({
          groupId: data.id,
          groupName: data.name
        }, function (ret, err) {
          if (ret.status == 'success') {
            // alert(JSON.stringify(ret.status));
          } else {
            alert(err.code);
          }
        });
      },
      failed: function failed() {}
    };


    HttpUploadService.upload($scope.group_logo, {
        success: function(logoUrl) {
            HttpService({ name: 'group/create', params: { user_id: user.id, name: $scope.groupModel.name, logo: logoUrl, description: $scope.groupModel.detail }, callback: callback });
        },
        failed: function() {
            alert('创建失败，请重试！');
        }
    },
    true);

  };

  $scope.groupList = function () {

    var callback = {
      success: function success(data) {
        $scope.dataGroupList = data.result;
        $scope.dataRecGroupList = data.rec_groups;

        $ionicSlideBoxDelegate.update();
        $ionicSlideBoxDelegate.$getByHandle('slideimgs').loop(true);

        // var groups = [];
        // for (var x in data.result) {
        //   groups.push({
        //     id: x.id,
        //     name: x.name,
        //     portraitUrl: x.logo
        //   });
        // }
        //
        // // 同步
        // RongCloudLibPlugin.syncGroup({
        //   groups: groups
        // }, function (ret, err) {
        //   if (ret.status == 'success') {
        //     // alert(JSON.stringify(ret.status));
        //   } else alert(err.code);
        // });
      },
      failed: function failed() {}
    };

    HttpService({ name: 'group/list', params: {user_id: UserService.getUserAcceptCache(true).id}, callback: callback });
  };

  $scope.groupDetail = function () {

    var groupID = $stateParams.groupID;

    var callback = {
      success: function success(data) {},
      failed: function failed() {}
    };

    HttpService({ name: 'group/show', params: { groupID: groupID }, callback: callback });
  };
});

ionicTea.controller('GroupChatCtrl', function ($scope, $state, $stateParams,$rootScope, $ionicScrollDelegate, $ionicHistory, $timeout, MsgService, HttpService, UserService, ImageService) {

  //聊天内容
  $scope.chatMsg = [];
  //聊天内容
  $scope.msgData;
  // 群详情
  $scope.groupModel = {};

  var group_id = $stateParams.id;
  var loginUser = UserService.getUserAcceptCache();
  var group_name = '';

  var isIOS = ionic.Platform.isWebView() && ionic.Platform.isIOS();

  $scope.back = function() {
    // $state.go($state.previous.name, $state.previous.params);
    $state.backToLastView();
    // $rootScope.back();
  };

  var msgCallback = {
    success: function success(msgs) {
      // add msgs
      $scope.$apply(function () {

        var length = msgs.length;
        console.log('msgs = ' + JSON.stringify(msgs));
        console.log('msgs.length = ' + msgs.length);

        var pos = length - 1;
        for (; pos >= 0; pos--) {

          var extraObj = JSON.parse(msgs[pos].content.extra)
          var targetUser = extraObj.user;

          $scope.chatMsg.push({
            headImg: targetUser.avatar,
            dir: msgs[pos].messageDirection === 'RECEIVE',
            userId: targetUser.id,
            msgContent: msgs[pos].content == null ? '' : msgs[pos].content.text,
            isImage: msgs[pos].objectName == 'RC:ImgMsg',
            image: msgs[pos].objectName == 'RC:ImgMsg' ? msgs[pos].content.imageUrl: '',
          });
        }
      });
    },
    failed: function failed(err) {}
  };

  console.log('set onReceiveListener');

  $scope.goToUserPage = function(id) {
    if (id == null) return;
    UserService.goToUserDetailPage(id);
  }

  // 8-8 receiver group
  // $rootScope.hasReceiver = false;
  // RongCloudLibPlugin.setOnReceiveMessageListener(function (ret, err) {
  //   // alert(JSON.stringify(ret.result.message));
  //   // console.log('OnReceive' + JSON.stringify(ret));
  //
  //
  //   if (err) {
  //     console.log(JSON.stringify(err));
  //     return;
  //   }
  //
  //   var extraObj = JSON.parse(ret.result.message.content.extra);
  //   var targetUser = extraObj.user;
  //   var msgFromGroup = extraObj.groupDetail;
  //
  //   if (group_id != msgFromGroup.id) return;
  //
  //   $scope.$apply(function () {
  //     $scope.chatMsg.push({
  //       headImg: targetUser.avatar,
  //       dir: true,
  //       msgContent: ret.result.message.content.text,
  //       userId: targetUser.id,
  //     });
  //     //滚动到最下方
  //     $ionicScrollDelegate.scrollBottom(true);
  //   });
  // });

  var receiverModel = {};
  receiverModel.name = 'chat-group';
  receiverModel.receiver = function(ret) {

    console.log('msg on GroupListener');
    console.log(JSON.stringify(ret));

    if ($state.is('chat_group')) {
      var extraObj = JSON.parse(ret.result.message.content.extra);
      var targetUser = extraObj.user;
      var msgFromGroup = extraObj.groupDetail;

      if (group_id != msgFromGroup.id) return;

      $scope.$apply(function () {
       $scope.chatMsg.push({
         headImg: targetUser.avatar,
         dir: true,
         userId: targetUser.id,
         msgContent: ret.result.message.content == null ? '' : ret.result.message.content.text,
         isImage: ret.result.message.objectName == 'RC:ImgMsg',
         image: ret.result.message.objectName == 'RC:ImgMsg' ? ret.result.message.content.imageUrl: '',
       });
       //滚动到最下方
       $ionicScrollDelegate.scrollBottom(true);
      });
    }
  };
  $rootScope.addReceiver(receiverModel);


  var loadLastestMsg = function loadLastestMsg(targetId) {
    MsgService.getLastestGroupMessages(targetId, msgCallback);
  };

  $scope.init = function () {
    loadLastestMsg(group_id);
    groupDetail();
  };

  $scope.goToGroupDetail = function (id) {
    $state.go('chat-group-detail', { id: id });
  };

  $scope.back = function () {
    // $state.go($state.previous.name, $state.previous.params);
    $state.backToLastView();
    // $rootScope.back();
  };

  $scope.isEditMode = false;
  $scope.onRightButtonClicked = function() {
    $scope.isEditMode = !$scope.isEditMode;

    // 提交
    if (!$scope.isEditMode) {
      var callback = {
        success: function success(data) {

        },
        failed: function failed() {

        }
      };

      HttpService({ name: 'group/update', params:
        {
          group_id: $scope.groupModel.id,
          name: $scope.groupModel.name,
          description: $scope.groupModel.description,
          announcement: $scope.groupModel.announcement,
        },
        callback: callback });
    }

  };

  var groupDetail = function groupDetail() {

    var callback = {
      success: function success(data) {
        $scope.groupModel = data;
        group_name = data.name;
        $scope.isMember = data.is_member;
      },
      failed: function failed() {}
    };

    var user = UserService.getUserAcceptCache();

    HttpService({ name: 'group/show', params: { group_id: group_id,
    user_id: user.id }, callback: callback });
  };

  $scope.groupQuit = function () {

    var user = UserService.getUserAcceptCache();

    var callback = {
      success: function success(data) {

        $state.go('tab.friends');
        // 融云退出群
        RongCloudLibPlugin.quitGroup({
          groupId: group_id
        }, function (ret, err) {
          if (err) {
            console.log(JSON.stringify(err));
          }
        });
      },
      failed: function failed(msg) {
        alert(msg);
      }
    };

    if ($scope.groupModel.is_creator) {
      HttpService({ name: 'group/delete', params: { group_id: group_id, user_id: user.id }, callback: callback });  
    } else {
      HttpService({ name: 'group/quit', params: { group_id: group_id, user_id: user.id }, callback: callback });
    }

  };

  $scope.groupJoin = function () {

    var user = UserService.getUserAcceptCache();

    var callback = {
      success: function success(data) {

        RongCloudLibPlugin.clearMessagesUnreadStatus({
            conversationType: 'GROUP',
            targetId: group_id,
          }, function (ret, err) {
              // alert(ret.status);
        });

        $state.go('chat_group', { id: group_id });
        // 融云加入群
        RongCloudLibPlugin.joinGroup({
          groupId: group_id,
          groupName: group_name
        }, function (ret, err) {

          if (err) {
            console.log(JSON.stringify(err));
          }

        });
      },
      failed: function failed() {}
    };

    HttpService({ name: 'group/join', params: { group_id: group_id, user_id: user.id }, callback: callback });
   };

   $scope.sendImage = function() {
    var callback = {
      success: function(imageURI) {

        var msg = {
          conversationType: 'GROUP',
          targetId: group_id,
          imagePath: imageURI,
          extra: ''
        };

        msg.extra = {};
        msg.extra.groupDetail = $scope.groupModel;
        msg.extra.user = loginUser;

         $scope.chatMsg.push({
            headImg: loginUser.avatar,
            dir: false,
            isImage: true,
            image: imageURI,
          });

        RongCloudLibPlugin.sendImageMessage(msg, function (ret, err) {
            if (ret.status == 'prepare') {

            }
                // alert(JSON.stringify(ret.result.message) );
            else if (ret.status == 'progress') {

            }
                // alert(ret.result.progress );
            else if (ret.status == 'success')
                alert(ret.result.message.messageId );
            else if (ret.status == 'error')
                alert(err.code );
          }
        );
      },
    };

    ImageService.pickImage(callback);
   }

  //发送消息
  $scope.sendMessage = function () {

    console.log("发送：" + $scope.msgData.message);

    if ($scope.msgData.message == null || $scope.msgData.message.length <= 0) {
      return;
    }

    var tempUser = UserService.getUserAcceptCache();

    $scope.chatMsg.push({
      headImg: tempUser.avatar,
      dir: false,
      msgContent: $scope.msgData.message
    });

    $scope.msgData.extra = {};
    $scope.msgData.extra.groupDetail = $scope.groupModel;
    $scope.msgData.extra.user = loginUser;

    // MsgService.sendMessage(group_id, $scope.msgData.message);
    MsgService.sendGroupMessage(group_id, $scope.msgData);

    delete $scope.msgData.message;
    //滚动到最下方
    $ionicScrollDelegate.scrollBottom(true);
  };

  $scope.inputUp = function () {
    if (isIOS) $scope.data.keyboardHeight = 216;
    $timeout(function () {
      $ionicScrollDelegate.scrollBottom(true);
    }, 300);
  };

  $scope.inputDown = function () {
    if (isIOS) $scope.data.keyboardHeight = 0;
    $ionicScrollDelegate.resize();
  };

  $scope.closeKeyboard = function () {
    //加不加吧  我也认不得
    // cordova.plugins.Keyboard.close();
  };
});

ionicTea.controller('FriendsListCtrl', function ($scope, $state, TeaFriendsPageSvc, $ionicHistory, $rootScope) {
  $scope.groupList = TeaFriendsPageSvc.fetchData();

  $scope.back = function () {
    // $state.go('tab.friends');
    //$state.backToLastView();
    $rootScope.back();
  };

  $scope.goToChat = function () {
    // RongCloudLibPlugin.clearMessagesUnreadStatus({
		//         conversationType: 'PRIVATE',
		//         targetId: id,
		//     }, function (ret, err) {
		//         // alert(ret.status);
		// });

    $state.go('chat');
  };

  $scope.goToChatGroup = function (id) {

    RongCloudLibPlugin.clearMessagesUnreadStatus({
        conversationType: 'GROUP',
        targetId: id,
      }, function (ret, err) {
          // alert(ret.status);
    });

    $state.go('chat_group', { id: id });
  };

  $scope.goToChatGroupDetail = function (id, isMember) {
    if (isMember) {
      $scope.goToChatGroup(id);
    } else {
      $state.go('chat-group-detail', { id: id });
    }

  };
});
